<template>
  <el-row :gutter="10">
    <el-col :span="5">
      <AtableClickable
        :fatherdata="blockslist"
        :fathercolumns="blockslist_columns"
        :fatherpagination="{ pageSize: 60 }"
        :acol="blockslistkey"
        :undulation="blockslistsec"
        v-on:emittext="blockquery"
        v-on:allblocks="nowblocksqurey"
        v-on:upblocks="nowblocksqurey"
        v-on:downblocks="nowblocksqurey"
        v-on:stayblocks="nowblocksqurey"
      />
      <el-alert
        :title="sql_alert_message"
        type="error"
        center
        :style="sql_alert_display"
        show-icon
        :closable="false"
      ></el-alert>
    </el-col>
    <el-col :span="19">
      <div :id="chartid" style="width: 100%; height: 300px"></div>
      <AntdTable
        :fatherdata="query_result"
        :fathercolumns="query_columns"
        :fatherpagination="{ pageSize: 40 }"
        :fatherscroll="{ x: '100%', y: 700 }"
      ></AntdTable>
    </el-col>
  </el-row>
</template>

<script>
import { query } from "@/apis/query";
import columnsnorm from "@/apis/columnsnorm";
import queryresnorm from "@/apis/queryresnorm";
import AntdTable from "@/components/AntdTable.vue";
import AtableClickable from "@/components/AtableClickable.vue";
//import Tableinput from "@/components/tableinput.vue";
import * as echarts from "echarts";
//import { inject } from "vue";

export default {
  components: {
    AntdTable,
    AtableClickable,
    //Tableinput
  },
  props: ["fathername"],
  mounted() {
    //const echarts = inject("echarts");
    //var echarts = inject("echarts");
    this.chartdom = echarts.init(document.getElementById(this.chartid));
    this.chartdom.setOption({});
    window.onresize = () => this.chartdom.resize("auto", "auto");

    //data
    query(
      "dbpytrol",
      "select block,undulation  from undulatingblock order by undulation desc"
    ).then((result, error) => {
      if (result) {
        if (result.data.errnum) {
          this.sql_alert_message = result.data.message;
          //sql_alert.style.visibility = "visible";
          this.sql_alert_display = "visibility:visible";
        } else {
          this.blockslist = result.data;
          this.blockslistkey = Object.keys(this.blockslist[0])[0];
          this.blockslistsec = Object.keys(this.blockslist[0])[1];
          this.blockslist_columns = columnsnorm(
            Object.keys(this.blockslist[0]),
            ["title", "dataIndex", "key"]
          );
          this.blockslist_columns.forEach((element) => {
            if (element["key"] === this.blockslistkey)
              element["slots"] = { customRender: "acol" };
            else if (element["key"] === this.blockslistsec)
              element["slots"] = { customRender: "undulation" };
          });
        }
      } else if (error) {
        console.log(error);
      }
    });
  },
  data() {
    return {
      blockslist: this.blockslist,
      blockslistkey: this.blockslistkey,
      blockslistsec: this.blockslistsec,
      blockslist_columns: this.blockslist_columns,
      sql_alert_message: "",
      sql_alert_display: "visibility:hidden",
      tabledisplay: false,
      query_result: [],
      query_columns: [],
      //tableinputtitle: "稳升区块录入",
      chartid: this.fathername + "chart" + Math.random(),
      chartdom: "",
      chartoption: "",
      chartcolor: "",
    };
  },
  methods: {
    nowblocksqurey(listen) {
      this.query_result = "";
      this.query_columns = "";
      this.sql_alert_display = "visibility:hidden";
      if (listen) {
        let now = new Date();
        /*
        let ym =
          " NY=" +
          now
            .getFullYear()
            .toString()
            .padStart(4, "0") +
          now
            .getMonth()
            .toString()
            .padStart(2, "0");
            */
        let ym =
          " NY>=" + (now.getFullYear() - 1).toString().padStart(4, "0") + "12";
        let sql =
          "SELECT NY,to_char(round(sum( tt.日产液),1)) as 日产液 ,to_char(round(sum(tt.日产油),1)) as 日产油 \
          ,to_char(round(sum(tt.老井产量),1)) as 老井产量,to_char(round(sum(tt.措施增油),1)) as 措施增油 \
          ,to_char(round(sum(tt.新井产量),1)) as 新井产量 \
          ,to_char(round(sum(tt.累产油),1)) AS 累产油 \
          ,AVG(tt.天数) as 天数 \
          from ( \
          select 油田||'_'||区块||'_'||计算层位 as 区块,NY \
          ,平均日产液 as 日产液,平均日产油 as 日产油 \
          ,老井平均日产油 as 老井产量 \
          ,新井平均日产油 as 新井产量,老井措施平均日增油 as 措施增油 \
          ,老井年累积产油* 10000-老井措施平均日增油*当月日历天数 AS 累产油 \
          ,当月日历天数 AS 天数 \
          from CQGC where ";
        for (let i = 0; i < listen.length; i++) {
          let bnarray = listen[i].split("_");
          if (bnarray.length < 3) {
            do {
              bnarray.push("--");
            } while (bnarray.length < 3);
          }
          for (let i = 0; i < bnarray.length; i++) {
            let text;
            if (i === 0) text = " (油田='";
            else if (i === 1) text = " and 区块='";
            else text = " and 计算层位='";
            sql = sql + text + bnarray[i] + "'";
          }
          if (i == listen.length - 1) sql = sql + " and " + ym + " ) ";
          else sql = sql + " and " + ym + " ) or";
        }
        sql = sql + " )tt group by NY order by NY";
        query("dbass", sql).then((result, error) => {
          if (result) {
            if (result.data.errnum) {
              this.sql_alert_message = result.data.message;
              this.sql_alert_display = "visibility:visible";
            } else {
              result.data = queryresnorm(result.data);

              let days = 0,
                qres = [],
                don = result.data[0]["日产油"];
              for (let mm = 0; mm < result.data.length; mm++) {
                let element = result.data[mm];
                if (mm == 0) {
                  element["理论递减率"] = "";
                  element["实际递减率"] = "";
                  element["理论递减产量"] = "";
                  element["实际递减产量"] = "";
                } else {
                  days = days + element["天数"];
                  element["天数"] = days;
                  element["理论递减率"] = (
                    100 *
                    (1 - Math.pow(0.87, mm / 12))
                  ).toFixed(1);
                  element["实际递减率"] = (
                    ((don - element["累产油"] / days) / don) *
                    100
                  ).toFixed(1);
                  element["理论递减产量"] = (
                    (don * element["理论递减率"]) /
                    100
                  ).toFixed(1);
                  element["实际递减产量"] = (
                    don -
                    element["累产油"] / days
                  ).toFixed(1);
                }
                delete element["天数"];
                delete element["累产油"];

                qres.push(element);
              }
              this.query_result = qres;

              this.query_columns = columnsnorm(
                Object.keys(this.query_result[0]),
                ["title", "dataIndex", "key"]
              );
            }
            return result.data;
          } else if (error) {
            console.log(error);
          }
        });
      }
    },
    blockquery(listen) {
      this.query_result = "";
      this.query_columns = "";
      this.sql_alert_display = "visibility:hidden";
      this.chartdom.setOption({ animation: true });
      if (listen) {
        let now = new Date();
        let ym =
          " NY>=" + (now.getFullYear() - 1).toString().padStart(4, "0") + "12";
        /* let sql =
          "SELECT 油田,区块,计算层位,NY,采油开井 \
          ,日产油,日产水,开发储量 as 地质储量,可采储量,注水开井 \
          ,分注开井,日注水能力,月注水量,综合含水,累积亏空,月注采比,采油总井 \
          ,注水总井,分注井合计 from HZSJ where " +
          ym;
        let sql =
          "SELECT 油田||'_'||区块||'_'||计算层位 as 区块,NY \
          ,to_char(round(日产油+日产水,1)) as 日产液,to_char(round(日产油,1)) as 日产油 \
          ,to_char(round(综合含水,1)) as 综合含水 ,to_char(round(累积亏空,4)) as 累计亏空 \
          ,to_char(round(月注采比,4)) as 月注采比 from HZSJ where " +
          ym;
          ,to_char(round(综合递减率,2)) as 综合递减,to_char(round(自然递减率,2)) as 自然递减率\
          */
        let sql =
          "select 油田||'_'||区块||'_'||计算层位 as 区块,NY \
          ,to_char(round(平均日产液,1)) as 日产液,to_char(round(平均日产油,1)) as 日产油 \
          ,to_char(round(100*(1-平均日产油/平均日产液),1)) as 含水,to_char(round(老井平均日产油,1)) as 老井产量 \
          ,to_char(round(新井平均日产油,1)) as 新井产量,to_char(round(老井措施平均日增油,1)) as 措施增油 \
          ,to_char(round(老井年累积产油* 10000,1)) AS 累产油 \
          ,当月日历天数 AS 天数 from CQGC where " +
          ym;
        let bnarray = listen.split("_");
        if (bnarray.length < 3) {
          do {
            bnarray.push("--");
          } while (bnarray.length < 3);
        }
        for (let i = 0; i < bnarray.length; i++) {
          let text;
          if (i === 0) text = " and 油田='";
          else if (i === 1) text = " and 区块='";
          else text = " and 计算层位='";
          sql = sql + text + bnarray[i] + "'";
        }
        sql = sql + " ORDER BY NY ASC";

        query("dbass", sql).then((result, error) => {
          if (result) {
            if (result.data.errnum) {
              this.sql_alert_message = result.data.message;
              this.sql_alert_display = "visibility:visible";
            } else {
              result.data = queryresnorm(result.data);
              let days = 0,
                qres = [],
                don = result.data[0]["日产油"];
              for (let mm = 0; mm < result.data.length; mm++) {
                let element = result.data[mm];
                if (mm == 0) {
                  element["理论递减率"] = "";
                  element["实际递减率"] = "";
                  element["理论递减产量"] = "";
                  element["实际递减产量"] = "";
                } else {
                  days = days + element["天数"];
                  element["理论递减率"] = (
                    100 *
                    (1 - Math.pow(0.87, mm / 12))
                  ).toFixed(1);
                  element["实际递减率"] = (
                    ((don - element["累产油"] / days) / don) *
                    100
                  ).toFixed(1);
                  element["理论递减产量"] = (
                    (don * element["理论递减率"]) /
                    100
                  ).toFixed(1);
                  element["实际递减产量"] = (
                    don -
                    element["累产油"] / days
                  ).toFixed(1);
                }
                delete element["天数"];
                delete element["累产油"];
                qres.push(element);
              }
              this.query_result = qres;
              this.query_columns = columnsnorm(
                Object.keys(this.query_result[0]),
                ["title", "dataIndex", "key"]
              );

              //chartdom
              let querydata = {
                NY: [],
                日产液: [],
                日产油: [],
                含水: [],
              };
              for (let key in querydata) {
                for (let element of this.query_result) {
                  querydata[key].push(element[key]);
                }
              }
              this.chartcolor = {
                日产液: "#91CC75",
                日产油: "#EE6666",
                含水: "#5470C6",
              };
              this.chartoption = {
                animation: false,
                xAxis: [
                  {
                    type: "category",
                    axisTick: {
                      alignWithLabel: true,
                    },
                    data: [
                      "去年12月",
                      "1月",
                      "2月",
                      "3月",
                      "4月",
                      "5月",
                      "6月",
                      "7月",
                      "8月",
                      "9月",
                      "10月",
                      "11月",
                      "12月",
                    ],
                  },
                ],
                legend: {
                  data: ["日产液", "日产油", "含水"],
                },
                yAxis: [
                  {
                    type: "value",
                    name: "日产液",
                    splitLine: {
                      show: false,
                    },
                    min: 0,
                    max: function (value) {
                      return (value.max * 1.3).toFixed(0);
                    },
                    axisLabel: {
                      formatter: "{value}  ",
                    },
                    axisLine: {
                      show: true,
                      lineStyle: {
                        color: this.chartcolor["日产液"],
                      },
                    },
                    offset: 40,
                    position: "left",
                  },
                  {
                    type: "value",
                    name: "日产油 ",
                    splitLine: {
                      show: false,
                    },
                    min: 0,
                    max: function (value) {
                      return (value.max * 1.3).toFixed(0);
                    },
                    axisLabel: {
                      formatter: "{value}",
                    },
                    axisLine: {
                      show: true,
                      lineStyle: {
                        color: this.chartcolor["日产油"],
                      },
                    },
                    position: "left",
                  },
                  {
                    type: "value",
                    name: "含水",
                    splitLine: {
                      show: false,
                    },
                    axisLabel: {
                      formatter: "{value} %",
                    },
                    min: function (value) {
                      let w = (value.min - 5).toFixed(0);
                      if (w > 0) return w;
                      else return 0;
                    },
                    max: function (value) {
                      let w = (value.max + 5).toFixed(0);
                      if (w < 100) return w;
                      else return 100;
                    },
                    axisLine: {
                      show: true,
                      lineStyle: {
                        color: this.chartcolor["含水"],
                      },
                    },
                    position: "right",
                  },
                ],
                series: [
                  {
                    name: "日产液",
                    yAxisIndex: 0,
                    type: "line",
                    data: querydata["日产液"],
                    color: this.chartcolor["日产液"],
                  },
                  {
                    name: "日产油",
                    yAxisIndex: 1,
                    type: "bar",
                    barWidth: "60%",
                    data: querydata["日产油"],
                    color: this.chartcolor["日产油"],
                  },
                  {
                    name: "含水",
                    yAxisIndex: 2,
                    type: "line",
                    data: querydata["含水"],
                    color: this.chartcolor["含水"],
                  },
                ],
                tooltip: {
                  trigger: "axis",
                  backgroundColor: "rgba(255, 255, 255, 0.6)",
                  axisPointer: {
                    type: "cross",
                  },
                },
              };
              this.chartdom.setOption(this.chartoption);
            }
          } else if (error) {
            console.log(error);
          }
        });
      } else {
        this.sql_alert_message = "SQL 输入不能为空";
        //sql_alert.style.visibility = "visible";
        this.sql_alert_display = "visibility:visible";
      }
    },
  },
};
</script>

<style scoped>
.el-alert {
  display: inline;
  visibility: hidden;
}

.el-select {
  display: inline-block;
}
.el-input {
  display: inline-block;
}
</style>
